import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
import queryString from "qs";
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  method: "POST",
  timeout: 5000, // request timeout
  withCredentials: true, //开启跨域并携带cookie,如果接口并不接收cookie验证的话则不需要
  headers: {
    accept: "*/*",
    "Content-Type": "application/x-www-form-urlencoded"
  },
  transformRequest: [
    function(data) {
      if (data instanceof FormData) {
        //上传文件的时候不需要转换
        return data;
      }
      return queryString.stringify(data); //利用对应方法转换格式
    }
  ]
});

// request interceptor
service.interceptors.request.use(
  config => {
    console.log(config, "发送请求");

    // 在发送请求之前
    if (store.getters.token) {
      config.headers["accessToken"] = getToken();
    }
    return config;
  },
  error => {
    // 对请求错误进行操作
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data;
    console.log(res);
    if (parseInt(res.Code) !== 0) {
      Message({
        message: res.Info || "Error",
        type: "error",
        duration: 5 * 1000
      });
      return Promise.reject(new Error(res.Info || "Error"));
    } else {
      return res;
    }
  },
  error => {
    console.log("err" + error); // for debug
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default service;
